from django.shortcuts import render,redirect
#密码解析
from django.contrib.auth.hashers import make_password, check_password
from django.http import HttpResponse,JsonResponse
#重定向用的
from django.core.urlresolvers import reverse
#数据分页模块
from django.core.paginator import Paginator
#Q模糊查询
from django.db.models import Q
from .. import models
import time,os
# Create your views here.
def userlist(request):
	users = models.Users.objects.all().exclude(status=3)
	#获取搜索的类型和内容
	types=request.GET.get('types')
	search=request.GET.get('search')
	print(types,search)
	
	# 实例化分页类
	if types == "all":
		users = models.Users.objects.filter(Q(id__contains=search)|Q(username__contains=search)|Q(phone__contains=search))
	elif types == "uid":
		users = models.Users.objects.filter(id__contains=search)
	elif types == "uname":
		users = models.Users.objects.filter(username__contains=search)
	elif types == "phone":
		users = models.Users.objects.filter(phone__contains=search)

	p = Paginator(users,2)
	#获取总的页码数
	sumpage=p.num_pages
	#分页操作
	# 获取当前页码
	page= int(request.GET.get('p',1))
	#判断页码设定位置
	if page < 4:
		#获取迭代页码数据
		prange = p.page_range[:5]
	elif page > sumpage-2:
		prange = p.page_range[-5:]
	elif page >3:
		prange = p.page_range[page-3:page+2]

	# 获取分页数据
	userlist= p.page(page)

	return render(request, 'myadmin/table-list.html',{"users":userlist,"prange":prange,"page":page,"sumpage":sumpage})

def adduser(request):

	if request.method=='GET':
		return render(request,'myadmin/form.html')
	elif request.method=='POST':
		info=request.POST.dict()
		info.pop('csrfmiddlewaretoken')
	#获取头像文件
	myfile = request.FILES.get("head_url",None)
	if not myfile:
		return HttpResponse("<script>alert('请选择头像');location.href=''</script>")
	#重写头像名	
	info["head_url"]=upload(myfile)
	#密码加密
	info['password'] = make_password(info['password'], None, 'pbkdf2_sha256')
	#存入数据库
	try:
		user=models.Users(**info)
		user.save()
		return HttpResponse("<script>alert('添加成功');location.href='"+reverse('myadmin_userlist')+"'</script>")	
	except:
		return HttpResponse("<script>alert('添加失败！');location.href=''</script>")

#删除用户		
def deluser(request):

	uid=request.GET.get('uid')
	user=models.Users.objects.get(id=uid)
	#添加删除状态
	user.status=3
	user.save()
	return HttpResponse("<script>alert('用户已删除！');location.href='"+reverse('myadmin_userlist')+"'</script>")

#修改用户	
def edituser(request):
	uid=request.GET.get('uid')
	# 判断请求
	if request.method == "GET":
		user=models.Users.objects.get(id=uid)
		return render(request,'myadmin/edit.html',{'cguser':user})
	elif request.method == "POST":
		olduser=models.Users.objects.get(id=uid)
		newuser=request.POST.dict()
		try:
			file = request.FILES.get("head_url",None)
			#获取头像文件 如果改了就存上
			if file :
				newurl=upload(file)
				os.remove("."+olduser.head_url)
				olduser.head_url=newurl
			#更新信息
			olduser.username=newuser["username"]
			olduser.age=newuser["age"]
			olduser.sex=newuser["sex"]
			olduser.phone=newuser["phone"]
			olduser.save()
			return HttpResponse("<script>alert('修改信息完成！');location.href='"+reverse('myadmin_userlist')+"'</script>")
		except :
			return HttpResponse("<script>alert('修改信息失败！');location.href=''</script>")
#重置密码 
def repwd(request):
	uid = request.GET.get('uid')
	user = models.Users.objects.get(id=uid)
	user.password = make_password('123456', None, 'pbkdf2_sha256')
	user.save()
	data={'data':"密码重置完成"}
	return JsonResponse(data)
#修改禁言状态
def restatus(request):
	uid = request.GET.get('uid')
	status = int(request.GET.get('status'))
	user = models.Users.objects.get(id=uid)
	user.status=status
	user.save()
	data={'data':"更改完成"}
	return JsonResponse(data)
def upload(myfile):
	# 新名字
	filename = str(time.time())+"."+myfile.name.split('.').pop()
	destination = open("./static/pics/"+filename,"wb+")
	for chunk in myfile.chunks():      # 分块写入文件  
		destination.write(chunk)  
	destination.close()
	# /static/pics/filename
	return '/static/pics/'+filename